package com.gaohe.controller;

import com.gaohe.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    //从配置文件中取得本地服务器的路径
    @Value("${fmt.path}")
    private String basePath;

    //图片上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //获取初始名字
        String originalFilename = file.getOriginalFilename();
        //使用uuid重新命名
        String s = UUID.randomUUID().toString();
        //获取文件后缀名
        int i = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(i);
        //拼接为最终文件名
        String finalName = s + substring;
        //通过File类来创建文件夹，上传到本地图片服务器
        File file1 = new File(basePath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        try {
            file.transferTo(new File(basePath + finalName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(finalName);

    }

    //图片下载，用于图片的回显
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        //输入流读取文件信息
        try {
            FileInputStream inputStream = new FileInputStream(basePath + name);
            //准备工作
            int len = 0;
            //数据暂存区
            byte[] bytes = new byte[1024];
            ServletOutputStream outputStream = response.getOutputStream();
            while ((len = inputStream.read(bytes)) != -1) {
                //response输出流向前端输出信息
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            inputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
